<!-- <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <input type="file">
  <img src="" alt="">
  <script>
    var input = document.querySelector('input');
    var img = document.querySelector('img');
    input.onchange = function(e){
      // console.dir(input)
      var file_img = this.files[0];
      // console.log(this.files[0].name)
      var reader = new FileReader();
      reader.readAsDataURL(file_img);
      reader.onload = function(){
        var f_name = (input.files[0].name.substring(input.files[0].name.lastIndexOf('.')));
        // console.log(f_name)
        var file_name = ['.jpg', '.png', '.gif', '.ico'];
        var flag = true;
        for(var i = 0; i < file_name.length; i++){
          if(f_name == file_name[i]){
            img.src = this.result;
            flag = true;
            break;
          }else{
            flag = false;
            continue;
          }
        }
       if(flag){
         alert('文件读取成功');
       }else{
         alert('文件格式不正确')
         input.value = '';
       }
      }
    }
  </script>
</body>
</html> -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <input type="file">
  <img src="" alt="">
  <script>
    var input = document.querySelector('input');
    var img = document.querySelector('img');
    var file_ary = ['.jpg', '.png', '.gif', '.ico'];
    input.addEventListener('change',function(){
      var file = input.files[0];
      var file_name = file.name
      var f_name = file_name.substring(file_name.lastIndexOf('.'))
      var reader = new FileReader();
      reader.readAsDataURL(file);
      reader.addEventListener('load',function(){
        var flag = true;
        for(var i = 0; i < file_ary.length; i++){
          if(f_name == file_ary[i]){
            img.src = this.result;
            flag = true;
            break;
          }else{
            flag = false;
            continue;
          }
        };
        if(flag){
          alert('文件上传成功');
        }else{
          alert('文件格式不正确');
          input.value = '';
        };
      });
    });
  </script>
</body>
</html>